<template>
  <view>
    <van-dropdown-menu>
      <van-dropdown-item :value="value1" :options="option1" />
      <van-dropdown-item :value="value2" :options="option2" />
    </van-dropdown-menu>

    <uni-card v-for="(item, index) in events" :key="item.id" :title="getTitle(item.tag)"
      :sub-title="getSubTitle(item.type)" :extra="formattedTime(item.createTime)" :thumbnail="getThumbnail(item.tag)"
      @click="cardClick">
      <view class="uni-body">
        {{item.content}}
      </view>
      <view slot="actions" class="card-actions">
        <view v-if="judgeLabel(item.type)" class="card-actions-item" @click="cardAction(item.tag,item.status,item.id)">
          <uni-icons :type="item.status === 0 ? 'close' : 'checkbox'" size="18" color="#999"></uni-icons>
          <text class="card-actions-item-text">{{ item.status === 0 ? '未完成' : '已完成' }}</text>
        </view>
        <view class="card-actions-item" @click="deleteCard(item.id)">
          <uni-icons type="trash" size="18" color="#999"></uni-icons>
          <text class="card-actions-item-text">删除</text>
        </view>
      </view>
    </uni-card>
    <van-dialog use-slot :show="show" title="饮水" show-cancel-button cancel-button-text="取消" confirm-button-text="确定"
      @confirm="onConfirm()" @cancel="onCancel()">
      <view class="dailog-body">
        <van-slider :value="sliderValue" min="0" max="1000" step="50" @change="handleSliderChange()" show-value
          bar-height="6" active-color="#4E9BFF" inactive-color="#E6E6E6" />
        <view class="slider-value">
          摄入水量: {{ sliderValue }} ml
        </view>
      </view>
    </van-dialog>
    <uni-fab ref="fab" :content="content" horizontal="right" vertical="bottom" direction="vertical" @trigger="trigger"
      @fabClick="fabClick" />
  </view>
</template>

<script>
  import {
    getEventList,
    addEvent,
    completeEvent,
    deleteEvent
  } from '@/api/event.js'

  export default {
    created() {
      this.userId = uni.getStorageSync('userId')
      this.refreshEvents()
    },
    data() {
      return {
        userId: 0,
        events: [],
        option1: [{
            text: '全部',
            value: 0
          },
          {
            text: '已完成',
            value: 1
          },
          {
            text: '待办',
            value: 2
          },
        ],
        option2: [{
            text: '今日',
            value: 'a'
          },
          {
            text: '日期1',
            value: 'b'
          },
          {
            text: '日期2',
            value: 'c'
          },
        ],
        value1: 0,
        value2: 'a',
        show: false, // 控制 Dialog 显示与隐藏
        sliderValue: 0, // 初始摄入水量
        affairCard: [{
          id: '', //事务id目前暂时使用时间戳作为id
          title: '服用5mg氨氯地平', //事务标题
          type: '定期事务', //事务类型
          timeStamps: 1744938000,
          createdTime: '2025.4.18 9:00', //事务创建时间
          time: '9:00', //用于展示的时间，只包含小时分钟
          label: '自定义', //事务标签，例如饮水，服药，睡眠
          status: 1, //事务状态，分为已完成1以及未完成0
          content: [{
            logid: '', //目前暂时使用logTime+log作为id
            logTime: '8:41', //日志时间
            log: '已完成', //日志内容
          }] //事务相关日志
        }],
        content: [{
            iconPath: '/static/images/icons/sleep.png',
            selectedIconPath: '/static/images/icons/sleep.png',
            text: '睡眠',
            active: false
          },
          {
            iconPath: '/static/images/icons/water.png',
            selectedIconPath: '/static/images/icons/water.png',
            text: '饮水',
            active: false
          },
          {
            iconPath: '/static/images/icons/food.png',
            selectedIconPath: '/static/images/icons/food.png',
            text: '饮食',
            active: false
          },
          {
            iconPath: '/static/images/icons/clock.png',
            selectedIconPath: '/static/images/icons/clock.png',
            text: '自定义',
            active: false
          }
        ]
      }
    },
    methods: {
      refreshEvents() {
        let userId = uni.getStorageSync('userId')
        getEventList(userId).then((res) => {
          this.events = res.data
        })
      },
      formattedTime(time) {
        const date = new Date(time);
        return date.toLocaleTimeString('en-US', {
          hour: '2-digit',
          minute: '2-digit',
          hour12: false
        });
      },
      generateLogId() {
        // 获取当前时间戳
        const timestamp = new Date().getTime();
        // 生成一个随机数 (比如 6 位)
        const randomNum = Math.floor(Math.random() * 1000000); // 可以根据需要调整随机数位数
        // 将时间戳与随机数组合，形成唯一的 logId
        return `${timestamp}-${randomNum}`;
      },
      getCurrentTime(formatType = 1) {
        const now = new Date(); // 获取当前时间
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以要加1
        const day = String(now.getDate()).padStart(2, '0');
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        if (formatType === 1) {
          // 返回年月日时分秒
          return `${year}.${month}.${day} ${hours}:${minutes}`;
        } else if (formatType === 2) {
          // 返回时分秒
          return `${hours}:${minutes}`;
        } else if (formatType === 0) {
          // 返回秒级时间戳
          return Math.floor(now.getTime() / 1000);
        } else {
          return null; // 默认返回 null
        }
      },
      getHoursDifference(timestamp1, timestamp2) {
        const diffInSeconds = Math.abs(timestamp1 - timestamp2); // 获取两个时间戳的绝对差值（秒数差）
        const diffInHours = diffInSeconds / 3600; // 秒数差转换为小时
        return diffInHours.toFixed(2);;
      },
      getThumbnail(tag) {
        if (tag === 2)
          return '/static/images/icons/sleep.png'
        else if (tag === 1)
          return '/static/images/icons/water.png'
        else if (tag === 3)
          return '/static/images/icons/food.png'
        return '/static/images/icons/clock.png'
      },
      handleSliderChange(e) {
        this.sliderValue = e.detail
      },
      judgeLabel(type) {
        if (type === 1)
          return false
        return true
      },
      cardClick(e) {
        console.log(e);
      },
      deleteCard(id) {
        deleteEvent(id).then((res)=>{
          uni.showToast({
            title: '删除成功',
            icon: 'none',
            duration: 1000
          });
          setTimeout(() => {
            this.refreshEvents()
          }, 1000);
          
        })
      },
      cardAction(tag, status, id) {
        console.log('===============>', status);
        switch (tag) {
          case 2:
            this.sleepAffair(status, id);
            break;
          case 1:
            this.quickAffair(status, id);
            break;
          case 4:
            this.customAffair(status, id);
            break;
          default:
            console.log('未知内容');
            break;
        }
      },
      trigger(e) {
        // this.content[e.index].active = !e.item.active
        switch (this.content[e.index].text) {
          case '睡眠':
            this.addSleepAffair()
            break;
          case '饮水':
            this.addDrinkAffair()
            break;
          case '饮食':
            this.addFoodAffair()
            break;
          case '自定义':
            this.addCustomAffair()
            break;
        }
        this.$refs.fab.close()
      },
      addSleepAffair() {
        let affair = {
          userId: this.userId,
          type: 2,
          tag: 2,
          status: 0,
          content: this.getCurrentTime(2)+'  开始睡眠'
        }
        addEvent(affair).then((res)=>{
          uni.showToast({
            title: '添加成功',
            icon: 'none',
            duration: 1000
          });
          setTimeout(() => {
            this.refreshEvents()
          }, 1000);
        })
      },
      addDrinkAffair() {
        this.show = true;
      },
      addFoodAffair() {
        const t = this
        uni.chooseImage({
          count: 1, //默认9
          sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], //album 从相册选图，camera 使用相机
          success: function(res) {
            t.urlToBase64(res.tempFilePaths[0])
          }
        })
      },
      addCustomAffair() {
        let affair = {
          userId: this.userId,
          type: 2,
          tag: 4,
          status: 0,
          content: this.getCurrentTime(2)+'  自定义事务'
        }
        addEvent(affair).then((res)=>{
          uni.showToast({
            title: '添加成功',
            icon: 'none',
            duration: 1000
          });
          setTimeout(() => {
            this.refreshEvents()
          }, 1000);
        })
      },
      urlToBase64(url) {
        uni.getFileSystemManager().readFile({
          filePath: url, //选择图片返回的相对路径
          encoding: 'base64', //编码格式
          success: res => { //成功的回调
            let base64 = 'data:image/jpeg;base64,' + res.data
            this.uploadPhoto(base64)
          },
          fail: (e) => {
            console.log("图片转换失败");
          }
        })
      },
      uploadPhoto(base64) {
        const t = this
        const ARK_API_KEY = '52dace76-aed2-4b56-9f73-5656e22c408b'
        uni.request({
          url: 'https://ark.cn-beijing.volces.com/api/v3/chat/completions',
          method: 'POST',
          header: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${ARK_API_KEY}`
          },
          data: {
            "model": "ep-20250412181957-8tnb6",
            "messages": [{
              "role": "user",
              "content": [{
                  "type": "image_url",
                  "image_url": {
                    "url": base64
                  }
                },
                {
                  "type": "text",
                  "text": "分析图中的食物大概有多少卡路里，直接给出菜名和一个数字，使用空格分隔，不需要分析以及多余的文字，例如“樱桃 60卡”"
                }
              ]
            }]
          },
          success: function(res) {
            console.log('请求成功:', res.data);
            const content = res.data.choices[0].message.content;
            // 正则：匹配 菜名（非空格字符） + 空格 + 数字（可能包含多个连续数字）
            const matchResult = content.match(/^(.+?)\s+(\d+)/); // 假设菜名在数字前，用空格分隔

            let dish = '';
            let calorie = '';
            if (matchResult) {
              dish = matchResult[1].trim(); // 提取菜名并去除前后空格
              calorie = matchResult[2]; // 提取数字
            } else {
              // 匹配失败时的默认处理
              dish = '未知菜品';
              calorie = '';
            }
            let affair = {
              userId: t.userId,
              type: 1,
              tag: 3,
              status: 1,
              value: calorie,
              content: t.getCurrentTime(2)+'  '+dish + ' ' + calorie + '卡'
            }
            addEvent(affair).then((res)=>{
              uni.showToast({
                title: '添加成功',
                icon: 'none',
                duration: 1000
              });
              setTimeout(() => {
                t.refreshEvents()
              }, 1000);
            })
          },
          fail: function(err) {
            console.log('请求失败:', err);
          }
        });
      },
      onConfirm() {
        let affair = {
          userId: this.userId,
          type: 1,
          tag: 1,
          status: 1,
          value: this.sliderValue,
          content: this.getCurrentTime(2) + '  摄入' + this.sliderValue + 'ml'
        }
        addEvent(affair).then((res)=>{
          uni.showToast({
            title: '添加成功',
            icon: 'none',
            duration: 1000
          });
          this.refreshEvents()
        })
        this.show = false
      },
      onCancel() {
        this.show = false
      },
      fabClick() {

      },
      sleepAffair(status, id) {
       completeEvent(id).then((res)=>{
         uni.showToast({
           title: '已完成',
           icon: 'none',
           duration: 1000
         });
         setTimeout(() => {
           this.refreshEvents()
         }, 1000);
       })
      },
      quickAffair(status, id) {

      },
      customAffair(status, id) {
        let log = {}
        switch (status) {
          case 0:
            this.affairCard[index].status = 1
            log = {
              logid: '',
              logTime: this.getCurrentTime(2),
              log: '已完成'
            }
            this.affairCard[index].content.push(log)
            break;
          case 1:
            this.affairCard[index].status = 0
            log = {
              logid: '',
              logTime: this.getCurrentTime(2),
              log: '修改为待办'
            }
            this.affairCard[index].content.push(log)
            break;
          default:
            console.log('未知状态');
            break;
        }
      },
      getTitle(tag) {
        const titles = {
          1: '饮水',
          2: '睡眠',
          3: '饮食',
          4: '自定义'
        };
        return titles[tag] || '';
      },
      getSubTitle(type) {
        const types = {
          1: '快捷事务',
          2: '定期事务'
        };
        return types[type] || '';
      },
    }
  }
</script>

<style>
  .card-actions {
    display: flex;
    flex-direction: row;
    justify-content: space-around;
    align-items: center;
    height: 45px;
    border-top: 1px #eee solid;
  }

  .card-actions-item {
    display: flex;
    flex-direction: row;
    align-items: center;
  }

  .card-actions-item-text {
    font-size: 12px;
    color: #666;
    margin-left: 5px;
  }

  .dailog-body {
    padding: 20px;
  }

  .slider-value {
    margin-top: 20px;
  }
</style>